﻿using Autofac.Features.Metadata;
using AutoMapper;
using IntelligentAgriculture.Contracts.Dto.Input;
using IntelligentAgriculture.Contracts.Dto.Output;
using IntelligentAgriculture.Contracts.Interface;
using IntelligentAgriculture.Domain.Entity;
using IntelligentAgriculture.Share.consts;
using IntelligentAgriculture.WebAPI.Application.Command;
using IntelligentAgriculture.WebAPI.Application.Command.UserCommand;
using IntelligentAgriculture.WebAPI.Filter;
using Lazy.Captcha.Core;
using MediatR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using NetTaste;
using System.Net;
using System.Text;
using static Dm.net.buffer.ByteArrayBuffer;

namespace IntelligentAgriculture.WebAPI.Controllers
{
    /// <summary>
    /// 用户控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    [AgricultureAuthorize]
    public class UserController : ControllerBase
    {
        /// <summary>
        /// Mediator
        /// </summary>
        private readonly IMediator _mediator;
        private readonly IMemoryCache _cache;
        private readonly ICaptcha _captcha;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="mediator"></param>
        public UserController(IMediator mediator, ICaptcha captcha, IMemoryCache cache)
        {
            _mediator = mediator;
            _captcha = captcha;
            _cache = cache;
        }

        ///// <summary>
        ///// 用户查询
        ///// </summary>
        ///// <remarks>用户查询的详细说明</remarks>
        ///// <returns></returns>
        //[HttpPost] // 请求谓词
        //public Results<List<Userinfo>> GetUsers()
        //{
        //  return Results<List<Userinfo>>.DataResult(_userService.GetUsers());
        //}

        /// <summary>
        /// 用户查询
        /// </summary>
        /// <remarks>用户查询的详细说明</remarks>
        /// <returns></returns>
        [HttpGet] // 请求谓词
        [AllowAnonymous]
        public async Task<Results<List<Userinfo>>> GetUsers()
        {
            var command = new UserGetUserCommand();
            return await _mediator.Send(command);
        }
        /// <summary>
        /// 获取验证码
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public Results<string> Captcha()
        {
            var id = Guid.NewGuid().ToString();
            var info = _captcha.Generate(id);
            // 有多处验证码且过期时间不一样，可传第二个参数覆盖默认配置。
            //var info = _captcha.Generate(id,120);
            _cache.Set<string>("imagesId", id);
            var stream = new MemoryStream(info.Bytes);
            return new Results<string> { Data = $"data:image/gif;base64,{Convert.ToBase64String(stream.ToArray())}", Code = 1, Msg = "验证码获取成功" };
        }
        ///// <summary>
        ///// 登录
        ///// </summary>
        ///// <param name="input">用户名与密码</param>
        ///// <returns></returns>
        //[HttpGet]
        //[AllowAnonymous]
        //public Results<Userinfo> Login(string UserName, string PassWord)
        //{
        //    var userDto = _userService.Login(UserName,PassWord);
        //    if (userDto != null)
        //    {
        //         _logger.LogInformation($"{userDto.NickName}登录了");
        //        var token = _tokenService.GenerateToken(userDto);
        //        return Results<Userinfo>.TokenResult(token, userDto);
        //    }
        //    _logger.LogError($"账号：{UserName}，密码：{PassWord}:登录失败：");
        //    return Results<Userinfo>.FailResult("用户或者密码不正确");
        //}
        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="UserName">用户名</param>
        /// <param name="PassWord">用户密码</param>
        /// <returns>返回用户信息</returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<Results<Userinfo>> Login(string UserName, string PassWord, string? code)
        {
            //判断验证码是否正确
            var imagesId = _cache.Get<string>("imagesId");
            if (!_captcha.Validate(imagesId, code))
            {
                return new Results<Userinfo> { Code = 400, Msg = "验证码错误" };
            }
            var command = new UserLoginCommand(UserName, PassWord);
            return await _mediator.Send(command);
        }
        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<ResultOutput<PermissionOutput>> me()
        {
            return new ResultOutput<PermissionOutput>
            {
                Code = ResultState.Success,
                Data = new PermissionOutput
                {
                    Avatar = "https://oss.youlai.tech/youlai-boot/2023/05/16/811270ef31f548af9cffc026dfc3777b.gif",
                    Nickname = "系统管理员",
                    Perms = new string[] {
                            "sys:menu:delete",
                            "sys:dept:edit",
                            "sys:dict_type:add",
                            "sys:dict:edit",
                            "sys:dict:delete",
                            "sys:dict_type:edit",
                            "sys:menu:add",
                            "sys:user:add",
                            "sys:role:edit",
                            "sys:dept:delete",
                            "sys:user:password_reset",
                            "sys:user:edit",
                            "sys:user:delete",
                            "sys:dept:add",
                            "sys:role:delete",
                            "sys:dict_type:delete",
                            "sys:menu:edit",
                            "sys:dict:add",
                            "sys:role:add"
                     },
                    Roles = new string[] { "ADMIN" },
                    UserId = 1770328009396588544,
                    Username = "admin"
                }
            };
        }
        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        [HttpDelete]
        [AllowAnonymous]
        public async Task<ResultOutput<int>> Logout()
        {
            return new ResultOutput<int> { Code = ResultState.Success, Data = 1 };
        }
        /// <summary>
        /// 获取全部路由
        /// </summary>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost]
        public async Task<ResultOutput<List<RoutesOutput>>> Routes()
        {

            return new ResultOutput<List<RoutesOutput>>
            {
                Code = ResultState.Success,
                Msg = "",
                Data = new List<RoutesOutput>
                {

                }
            };
        }
        /// <summary>
        /// 新增人员
        /// </summary>
        /// <param name="user">新增信息</param>
        /// <returns></returns>
        [HttpPost]
        [AllowAnonymous]
        public async Task<Results<int>> AddUser(AddUserInput user)
        {
            var command = new AddUserCommand(user);
            return await _mediator.Send(command);
        }
        /// <summary>
        /// 发送手机验证码
        /// </summary>
        /// <param name="Recipient_Mobile_Num"></param>
        /// <returns></returns>
        [HttpGet]
        [AllowAnonymous]
        public async Task<CallPhoneDto> CallPhone(string personage_Phone)
        {
            string PostUrl = "http://106.ihuyi.com/webservice/sms.php?method=Submit";
            //登录“互亿无线网站”查看用户名 登录用户中心->验证码通知短信>产品总览->API接口信息->APIID
            string account = "C22738545";
            //登录“互亿无线网站”查看密码 登录用户中心->验证码通知短信>产品总览->API接口信息->APIKEY
            string password = "29f28f04254d9bae0a91552da8b8504c";
            //接收短信的用户的手机号码
            string mobile = personage_Phone;
            //随机生成四位数 可以模仿向用户发送验证码
            Random rad = new Random();
            int mobile_code = rad.Next(1000, 10000);   //生成随机数
            string content = "您的验证码是：" + mobile_code + " 。请不要把验证码泄露给其他人。";

            string postStrTpl = "account={0}&password={1}&mobile={2}&content={3}";  //用户名+密码+注册的手机号+验证码

            UTF8Encoding encoding = new UTF8Encoding();  //万国码
            //将 account, password, mobile, content 这四个内容添加到postStrTpl字符串当中
            //并利用encoding.GetBytes()将括号里面的字符串转化为二进制类型
            byte[] postData = encoding.GetBytes(string.Format(postStrTpl, account, password, mobile, content)); //将字符串postStrTpl中的格式项替换为四个个指定的 Object 实例的值的文本等效项。再转为二进制数据

            //新建一个请求对象
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(PostUrl);//对统一资源标识符 (URI) 发出请求。 这是一个 abstract 类。
            myRequest.Method = "POST";
            myRequest.ContentType = "application/x-www-form-urlencoded";
            myRequest.ContentLength = postData.Length;

            Stream newStream = myRequest.GetRequestStream();
            //间postData合并到 PostUrl中去
            newStream.Write(postData, 0, postData.Length);
            newStream.Flush();
            newStream.Close();


            //以http://106.ihuyi.com/webservice/sms.php?method=Submit&account=你的APIID&password=你的APIKEY&mobile=接收短信的用户的手机号码&content=您的验证码是：" + mobile_code + " 。请不要把验证码泄露给其他人。"    发起https请求   并获取请求结果
            HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();

            if (myResponse.StatusCode == HttpStatusCode.OK)
            {
                return new CallPhoneDto
                {
                    Code = State.Success,
                    Msg = "验证码发送成功",
                    Data = mobile_code
                };
            }
            else
            {
                return new CallPhoneDto
                {
                    Code = State.Success,
                    Msg = "访问失败"
                };
            }
        }
    }
}